<template>
  <div class="novel-container">
    <!-- 顶部导航栏 -->
    <div class="nav-bar">
      <van-icon name="arrow-left" size="20" color="#fff" @click="back"/>
      <div class="nav-actions">
        <van-icon v-if="isLoadings==false" name="down" size="20" color="#fff" @click="xz"/>
        <van-loading v-if="isLoadings" type="spinner" size="24px" color="#1989fa"/>
        <van-icon v-if="isLoading==false" name="replay" size="20" color="#fff" @click="showLoading"/>
        <van-loading v-if="isLoading" type="spinner" size="24px" color="#1989fa"/>
      </div>
    </div>

    <!-- 小说信息区域 -->
    <div class="novel-info">
      <div class="book-basic">
        <img :src="novel.url" class="book-cover"/>
        <div class="book-details">
          <h1 class="book-title">{{ novel.name }}</h1>
          <div class="author">
            <van-icon name="manager-o"/>
            <span>{{ novel.pname }}</span>
          </div>
          <div class="book-stats">
            <div class="rating">
              <span class="score" v-if="score.average!=null">{{ score.average }}分</span>
              <span class="score" v-if="score.average==null">暂无评分</span>
              <div class="stars">
                <van-rate v-model="score.average/2" readonly allow-half color="#ffd21e" void-icon="star"
                          void-color="#eee"/>
              </div>
              <span class="review-count">{{ score.number }}人点评</span>
            </div>
            <div class="reading-count">
              <span>{{ Math.round(this.num / 10000) }}</span>
              <span class="reading-label">万字</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 简介 -->
      <div class="book-intro">
        <h3>小说简介</h3>
        <p class="intro-text" :class="{ 'expanded': showFullIntro }">
          {{ novel.introduction }}
        </p>
        <div class="expand-btn" @click="toggleIntro">
          <van-icon :name="showFullIntro ? 'arrow-up' : 'arrow-down'"/>
        </div>
      </div>

      <!-- 标签 -->
      <div class="tags">
        <span v-if="novel.sort==1" class="tag">玄幻</span>
        <span v-if="novel.sort==2" class="tag">都市</span>
        <span v-if="novel.sort==3" class="tag">爱情</span>
        <span v-if="novel.sort==4" class="tag">历史</span>
      </div>

      <!-- 目录区域 -->
      <div class="chapter-info">
        <div class="chapter-header" @click="Contents">
          <span>查看目录</span>
          <span class="update-info">更新至{{ this.wz }}章 ></span>
        </div>
      </div>

      <van-popup v-model="show" position="bottom" :style="{ height: '60%' }">
        <van-nav-bar title="添加书评" right-text="发表" @click-right="submit"/>
        <van-rate
            style="margin-top: 20px"
            v-model="rating"
            :size="25"
            color="#ffd21e"
            void-icon="star"
            void-color="#eee"
        />
        <van-field
            v-model="scoerbook"
            placeholder="优质书评会优先展示哦！"
            rows="3"
            autosize
            style="background-color: #F1F1F1;width:90%;height: 250px;margin-top: 10px;margin-left: 20px"
        />
      </van-popup>

      <div style="margin-top: 10px">
        <div style="background-color: white;height: 40px">
          <van-button type="primary" style="height: 30px;float: left;margin-top: 5px" icon="edit" round
                      @click="bookToWriteReview">写书评
          </van-button>
          <div style="padding-top: 10px;float: left;width: 100px;height: 30px;margin-left: 40px">书评</div>
          <van-icon style="float: right;margin-top: 15px;margin-right: 10px" name="arrow" @click="goToWriteReview"/>
        </div>
        <van-cell v-for="(review, index) in reviews" :key="index">
          <div>
            <van-image style="width: 50px;height: 50px;float: left" :src="review.userurl" round/>
            <span style="margin-left: 20px;float: left">{{ review.username }}</span>
            <div style="float: left;margin-top: 25px;margin-left: -45px">
              <van-rate v-model="review.score/2" readonly allow-half color="#ffd21e" void-icon="star"
                        void-color="#eee"/>
            </div>

            <div>
              <span style="float: left;margin-top: 20px;width: 100%">{{ review.comment }}</span>
            </div>
            <div>
              <span style="float: left;margin-top: 20px">{{ review.commenttime }}</span>
              <van-icon style="float: right;margin-top: 20px" size="20px" name="chat-o" @click="showComment(review.id)"/>
            </div>
          </div>
        </van-cell>
      </div>

    </div>


    <van-popup style="width: 80%;height: 150px" v-model="showss">
      <div>
        <div style="margin-top: 20px">
           <span>小说下载需要{{this.as}}金币,是否确认下载</span>
        </div>
        <div style="margin-top: 20px">
          <van-button type="danger" style="float: right;margin-right: 30px" @click="showss=false">取消</van-button>
          <van-button type="primary" style="float: left;margin-left: 30px" @click="Contentsbook">确认</van-button>
        </div>
      </div>
    </van-popup>


    <!-- 底部操作按钮 -->
    <div class="bottom-actions">
      <van-button class="add-shelf" plain type="primary" @click="addbooks(novel.id,uid)">加入书架</van-button>
      <van-button class="start-read" type="primary" @click="book(novel.id)" block>开始阅读</van-button>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "Noveldetails",
  data() {
    return {
      novel: {},
      download: [],
      score: {},
      catalog: [],
      num: 0,
      wz: 0,
      showFullIntro: false,
      isLoading: false,
      isLoadings: false,
      reviews: [],
      sj: 0,
      show: false,
      rating: 0,
      scoerbook: '',
      books: [],
      sjs: 0,
      sjss: 0,
      bookscore: {},
      showss:false,
      as:0,
      user:{},
      uid:0,
      user1:{},
      date:"",
    }
  },
  created() {

    this.findbyid();
    this.findReviews();
    this.scores();
    this.list();
    this.dl();
    this.user1=localStorage.getItem("user");
    let user1=JSON.parse(this.user1);
    console.log(user1.id)
    this.uid=user1.id;
    this.addHistory();

  },
  methods: {
    addbooks(pid,uid){
      axios.post('http://localhost:9999/api-user/user/addbooks?pid='+pid+'&uid='+uid).then(res => {
        if (res.data.code == 1){
          this.$toast.success('添加成功');
        } else {
          this.$toast.success(res.data.message);
        }
      })
    },
    addHistory() {
      console.log("开始添加阅读历史")
      console.log(this.$route.query.id)
      this.axios.post(`http://localhost:9999/api-user/user/addhistory?uid=${this.uid}&pid=`+this.$route.query.id)
    },
    showComment(id){
      this.$router.push({path: '/novelreply',query: {pid: id,id:this.$route.query.id}})
    },

    submit() {
      let users = JSON.parse(this.user);
      this.bookscore.uid = users.id;
      this.bookscore.score = this.rating * 2;
      this.bookscore.pid = this.$route.query.id;
      this.bookscore.comment = this.scoerbook;

      axios.post(`http://localhost:9999/api-novel/score/add`, this.bookscore).then(res => {
        if (res.data.code == 1) {
          this.show = false;
          this.rating = 0;
          this.scoerbook = '';
          this.scores();
          this.$toast.fail('评论成功');
          axios.post("http://localhost:9999/api-task/dailyTasks/updateCommentNumber?userId="+users.id).then(res=>{
            console.log("评论数+1")
          })
        }
      })

    },

    dl() {
      this.user = localStorage.getItem('user');
      // console.log("user"+this.user)
      // let users=JSON.parse(this.user);
      // console.log("users+"+users.id)
    },

    xz(){
      this.as = (this.wz) * 10;
      this.showss=true;
    },

    async Contentsbook() {
      this.showss=false;
      if (this.user != null) {
        let users = JSON.parse(this.user);
        axios.post(`http://localhost:9999/api-user/user/xz?id=${users.id}&userglod1=${this.as}`).then(async res => {
          if (res.data.code == 1) {
            this.isLoadings = true; // 立即设置为true，触发加载动态效果显示
            await this.bookss();
            let a = this.sjss + this.sjs;
            // 模拟异步操作，这里也可以根据真实的异步操作来替换掉setTimeout
            await new Promise((resolve) => setTimeout(() => {
              this.isLoadings = false;
              resolve();
            }, a));
          }else{
            this.$toast.fail(res.data.message);
          }
        })
      } else {
        this.$toast.fail('请先登录');
        // this.$router.push('/login');
      }
    },

    async bookss() {
      let startTimeRequest = Date.now();
      let a=this.$route.query.id;
      const res = await axios.post('http://localhost:9999/api-novel/books/findallbyid?pid=' + a);
      let endTimeRequest = Date.now();
      let requestTime = endTimeRequest - startTimeRequest;
      console.log("网络请求耗时: " + requestTime);

      this.download = res.data;
      for (var i = 0; i < this.download.length; i++) {
        this.books.push(this.download[i].title + this.download[i].content);
      }

      await this.booksss();

      let endTime = Date.now();
      this.sjs = endTime - startTimeRequest; // 这里修改为从最开始网络请求发起时算总耗时
      console.log("sjs（包含网络请求和后续所有操作）: " + this.sjs);
    },

    booksss() {
      let startTime = Date.now();
      console.log("开始执行下载相关操作");
      let content = '';
      this.books.forEach(chapter => {
        content += chapter;
      });
      const blob = new Blob([content], {type: 'text/plain;charset=utf-8'});
      const downloadUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = downloadUrl;
      a.download = this.novel.name + '.txt';
      a.click();
      this.books = [];
      let endTime = Date.now();
      this.sjss = endTime - startTime;
      console.log("sjss（下载操作耗时）: " + this.sjss);
    },


    bookToWriteReview() {
      if (this.user != null) {
        this.show = true;
      } else {
        this.$toast.fail('请先登录');
      }
    },
    book(id) {
      this.$router.push({
        path: '/xs1',
        query: {
          id: 1,//章节id
          pid: id, //书籍id
        }
      })
    },
    back() {
      this.$router.push("/");
    },
    goToWriteReview() {
      this.$router.push({path: '/writereview', query: {id: this.$route.query.id}})
    },

    Contents() {
      this.$router.push({path: '/novelcontents', query: {id: this.$route.query.id}})
    },

    scores() {
      axios.post('http://localhost:9999/api-novel/score/list?pid=' + this.$route.query.id).then(res => {
        if (res.data.code == 1) {
          this.score = res.data.data;
        }
      })
    },

    findReviews() {
      axios.post('http://localhost:9999/api-novel/score/findbyid?pid=' + this.$route.query.id).then(res => {
        if (res.data.code == 1) {
          this.reviews = res.data.data;
        }
      })
    },

    list() {
      let startTime = Date.now();
      axios.post('http://localhost:9999/api-novel/books/list?pid=' + this.$route.query.id).then(res => {
        this.catalog = res.data;

        for (var i = 0; i < this.catalog.length; i++) {
          this.num += this.catalog[i].word_count;
        }
        for (let i = 0; i < this.catalog.length; i++) {
          if (i === this.catalog.length - 1) {
            this.wz = this.catalog[i].chapter_id;
          }
        }

        let endTime = Date.now()
        this.sj = endTime - startTime;
      })
    },

    showLoading() {
      this.num = 0;
      this.wz = 0;
      this.isLoading = true;
      // 模拟异步操作
      setTimeout(() => {
        this.list();
        this.findbyid();
        this.findReviews();
        this.scores();
        this.isLoading = false;
      }, this.sj);
    },

    findbyid() {
      let a=this.$route.query.id;
      axios.get('http://localhost:9999/api-novel/novel/findbyid?id=' +a).then(res => {
        if (res.data.code == 1) {
          this.novel = res.data.data;
        }
      })
    },
    toggleIntro() {
      this.showFullIntro = !this.showFullIntro;
    }
  }
}
</script>

<style scoped>
.novel-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  z-index: 100;
}

.nav-actions {
  display: flex;
  gap: 20px;
}

.novel-info {
  background: linear-gradient(to bottom, #e1c299, #f5f5f5);
  padding: 20px 16px;
  padding-top: 50px;
  margin-bottom: 60px;
}

.book-basic {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.book-cover {
  width: 120px;
  height: 160px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.book-details {
  flex: 1;
  color: #fff;
}

.book-title {
  font-size: 24px;
  margin: 0 0 8px 0;
}

.author {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 16px;
  font-size: 14px;
}

.book-stats {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.rating {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.score {
  font-size: 24px;
  font-weight: bold;
}

.review-count {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

.reading-count {
  text-align: right;
  font-size: 12px;
}

.reading-label {
  color: rgba(255, 255, 255, 0.8);
  margin-left: 4px;
}

.book-intro {
  background: #fff;
  padding: 16px;
  border-radius: 12px;
  margin-bottom: 16px;
}

.intro-text {
  font-size: 14px;
  line-height: 1.6;
  color: #666;
  max-height: 60px;
  overflow: hidden;
  transition: max-height 0.3s;
}

.intro-text.expanded {
  max-height: none;
}

.expand-btn {
  text-align: center;
  color: #999;
  margin-top: 8px;
}

.tags {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.tag {
  padding: 4px 12px;
  background: rgba(225, 194, 153, 0.2);
  border-radius: 16px;
  font-size: 12px;
  color: #e1c299;
}

.chapter-info {
  background: #fff;
  padding: 16px;
  border-radius: 12px;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.update-info {
  color: #999;
  font-size: 12px;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 12px;
  padding: 12px 16px;
  background: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}

.add-shelf {
  flex: 1;
}

.start-read {
  flex: 2;
}
</style>
